//
//  TopLevelEntity.swift
//  Core
//
//  Created by raymond Peng on 2018/11/9.
//  Copyright © 2018 raymond Peng. All rights reserved.
//

import Foundation
import Domain

/// 响应实体
struct ResponseTopLevelEntity<T: Decodable>: Decodable {
    let message: String?
    let code: Int?
    let data: T?
}

typealias TopLevelDataResult<T: Decodable> = (ResponseTopLevelEntity<T>?, DataError?)

func deserializeTopLevelObjWith<T: Decodable>(data: Data) -> TopLevelDataResult<T> {
    let decoder = JSONDecoder()
    do {
        let entity = try decoder.decode(ResponseTopLevelEntity<T>.self, from: data)
        // 在这里联入一个业务上的逻辑: 当服务端响应中包含的自定义状态值小于 0, 则认为是逻辑上的错误.
        guard (entity.code ?? -1) >= 0 else {
            let err = DataError(errorCode: entity.code ?? -1, errorMessage: entity.message ?? "")
            return (entity, err)
        }
        return (entity, nil)
    } catch {
        let err = DataError.deserializationError()
        return (nil, err)
    }
}
